<template>
  <div id="Account">
    <card class="account">
        <div slot="content" class="card-demo-flex card-demo-content01">
            <div class="borderR">
                <p>{{year}}年</p>
                <span>{{mouth}}<i> 月</i></span>
                <datetime :min-year=2000 format="YYYY-MM" @on-change="change" :end-date="today" year-row="{value}年" month-row="{value}月" confirm-text="确定" cancel-text="取消"></datetime>
            </div>
            <div>
                <p>支出({{exp}})</p>
                <span>{{totalList.expend | currency('',n1)}}</span>
            </div>
            <div>
                <p>收入({{inc}})</p>
                <span>{{totalList.income | currency('',n2)}}</span>
            </div>
        </div>
    </card>

    <group>
        <tab :line-width=0 v-model="indexTab">
            <tab-item class="vux-center" v-for="(item, index) in tab" :key="index">{{item}}</tab-item>
        </tab>
        <div v-model="indexTab">
            <div v-show="indexTab==0">
                 <scroller v-show="isShow" height="-195" lock-x @on-scroll-bottom="onScrollBottom" ref="scrollerBottom" :scroll-bottom-offst="10">
                      <div class="box2">
                          <div class="tab-group" v-for="(item, key) in monthList">
                              <cell :title="(item.totaldays-key)+'日-'+item.time">
                                  <span slot class="pay">支出:{{item.expend}}&nbsp;&nbsp;&nbsp;&nbsp;收入:{{item.income}}</span>
                              </cell>
                              <cell-form-preview :list="item.day"></cell-form-preview>
                          </div>
                          <load-more tip="正在加载" v-show="onFetching"></load-more>
                          <load-more :show-loading="false" :tip="text" v-show="onAll" background-color="#fbf9fe"></load-more>
                      </div>
                  </scroller>
              </div>
              <div  v-bind:style="{height:heightMax+'px'}" style="overflow-y: auto" v-show="indexTab==1">
                    <div class="tab-group">
                      <cell :title="'收入结构报表'">
                        <span slot class="pay">相比上月收入:{{incomeMoneys}}</span>
                      </cell>
                      <div id="main"></div>
                    </div>
                    <div class="tab-group">
                      <cell :title="'支出结构报表'" class="pay-tit">
                        <span slot class="pay">相比上月支出:{{expendMoneys}}</span>
                      </cell>
                      <div id="main2"></div>
                    </div>
              </div>
        </div>
    </group>


  </div>
</template>

<script>
  import {  Card , Cell , Group , Tab, TabItem,LoadMore ,Datetime ,Swiper, SwiperItem, CellFormPreview , Scroller , Divider,cookie } from 'vux'
  import echarts from 'echarts/lib/echarts'
  import 'echarts/lib/chart/pie'
  import 'echarts/lib/component/tooltip'
  import 'echarts/lib/component/title'
  import { Decrypt} from '../../aes/aes';
  import { sorts,sign } from '../../aes/make';
  import payType from '../../mock/payType';
  import { getMoneyFlow,getImgMoneyFlow } from '../../mock/api';
  export default {
    components: {
        Group,
        Card,
        Cell,
        LoadMore,
        Datetime,
        Tab,
        TabItem,
        Swiper,
        SwiperItem,
        CellFormPreview,
        Scroller,
        Divider
    },
    data () {
      return {
        n1:2,
        n2:2,
        exp:'元',
        inc:'元',
        height:0,
        year:'2017',
        mouth:'8',
        page:1,
        todayNum:'2018-08-13',
        today:'2018-08-13',
        pagesize:15,
        totalList:{},
        bottomCount: 20,
        indexTab:0,
        selPullUp:true,
        isShow:true,
        tab: ['明细','报表'],
        showList1: true,
        scrollTop: 0,
        onFetching: true,
        onAll:false,
        monthList: {},
        dayList:[],
        listArr:{},
        // 初始化空对象
        chart: null,
        // 初始化图表配置
        incomeMoneys:'',
        income:'',
        incomeData: [{
            value: 12,
            name: '充值'
        }, {
            value: 31.1323,
            name: '矮富帅'
        }, {
            value: 18.13132323,
            name: '高富挫'
        }] ,
        incomeName:[],
        expendMoneys:'',
        expend:'',
        expendData: [{
            value: 12,
            name: '充值'
        }, {
            value: 31.1323,
            name: '矮富帅'
        }, {
            value: 18.13132323,
            name: '高富挫'
        }] ,
        expendName:[],
        text:'已加载全部数据'
      }
    },
    created () {
      let vue = this
      vue.updateTitle('账本');
      vue.updateGreenRightNum(0);
    },
    computed:{
      heightMax:function(){
        this.height=window.screen.availHeight;
        return this.height-195;
      }
    },
    mounted(){
        this.setToday();
        this.transactionList(this.page,this.pagesize,this.today);
        this.$nextTick(() => {
          this.$refs.scrollerBottom.reset({top: 0})
        })
        this.$nextTick(function() {
            this.drawGraph() ;
        });
    },
    methods: {
        change (value) {
            this.todayNum=value+'-01';
            this.year= value.slice(0,4);
            var zero=value.slice(5,6);
            this.mouth=value.slice(5,7);
            this.page=1;
            this.transactionList(this.page,this.pagesize,this.todayNum);
            this.drawGraph();
        },
        // 明细列表
        onScrollBottom () {
            if (this.onFetching) {
                // do nothing
            } else {
                var maxpage=Math.ceil(this.totalList.total/this.pagesize);
                if(this.page>maxpage && maxpage>=1){
                    this.onAll = true;
                    this.text='已加载全部数据';
                  this.onFetching = false;
                }else{
                    this.onFetching = true;
                  this.onAll = false;
                    this.page++;
                    this.transactionList(this.page,this.pagesize,this.todayNum);
                    this.$nextTick(() => {
                        this.$refs.scrollerBottom.reset()
                    })
                }
            }
        },
        // 绘图
        drawGraph() {
            var sel=true;
            var sel2=true;
            var color=['#f4f0c4','#e4f2ff','#ec7b49','#c7623f','#c5c5b2'];
            var color1=['#f4f0c4','#e4f2ff','#ec7b49','#c7623f','#c5c5b2'];
            var uid=cookie.get('uid');
            var access_token=cookie.get('access_token');
            var so=sorts();
            var json={
              month:this.year+'-'+this.mouth+'-'+'01',
              sorts:so,
              uid:uid,
              access_token:access_token
            }
            var si=sign(json);
            json['sign']=si;
            getImgMoneyFlow(json).then((res)=>{
                if(res.code==40013){
                    vue.$router.push({name: 'login', params: {}});
                    return false;
                }
                var jm=Decrypt(res.data);
                jm=JSON.parse(jm);
                // 收入
                this.income=jm.income_moneys;
                var money=jm.income_moneys-jm.last_month_incomes;
                money=money.toFixed(2);
                if(money>=0){
                    this.incomeMoneys='+'+money;
                }else{
                  this.incomeMoneys=money;
                }
                this.incomeData=[];
                for(var i in jm.income_money_type){
                    var json={
                        name:payType[jm.income_money_type[i].pay_type],
                        value:parseFloat(jm.income_money_type[i].money)
                    }
                   this.incomeData.push(json);
                   this.incomeName.push(json.name);
                }
                if(this.incomeData.length==1 && this.incomeData[0].name==undefined){
                  color=['#ddd'];
                  sel=false;
                }
                if(this.incomeData.length){
                    this.drawBox(this.incomeData,'总收入',this.income,'main',color,sel);
                }else{
                    this.drawBox(this.incomeData,'',this.income,'main',color,sel);
                }

                // 支出
                this.expend=jm.expend_moneys;
                var money1=jm.expend_moneys-jm.last_month_expends;
                money1=money1.toFixed(2);
                if(money1>=0){
                    this.expendMoneys='+'+money1;
                }else{
                    this.expendMoneys=money1;
                }
                this.expendData=[];
                for(var i in jm.expend_money_type){
                  if(jm.expend_money_type[i].pay_type){
                    jm.expend_money_type[i].gc_id=payType[jm.expend_money_type[i].pay_type];
                  }else if(jm.expend_money_type[i].other){
                    jm.expend_money_type[i].gc_id='其它';
                  }
                   var json={
                        name:jm.expend_money_type[i].gc_id,
                        value:parseFloat(jm.expend_money_type[i].money)
                    }
                   this.expendData.push(json);
                   this.expendName.push(json.name);
                }

                if(this.expendData.length==1 && this.expendData[0].name==undefined){
                  color1=['#ddd'];
                  sel2=false;
                }
                if(this.expendData.length){
                    this.drawBox(this.expendData,'总支出',this.expend,'main2',color1,sel2);
                }else{
                    this.drawBox(this.expendData,'',this.expend,'main2',color1,sel2);
                }

            })
        },
        // 绘图方法
        drawBox(data,title,total,id,color,sel){
            var v=total;
            this.chart = echarts.init(document.getElementById(id))
            // 皮肤添加同一般使用方式
            this.chart.showLoading()
            var that = this
            this.chart.setOption({
                tooltip: {
                    trigger: 'item',
                    formatter: "{b} <br/>{c}: {d}%",
                    show:sel
                },
                title: {
                    text:title,
                    left:'center',
                    top:'28%',
                    padding:[24,0],
                    textStyle:{
                        color:'#999',
                        fontSize:13,
                        fontWeight:400,
                        align:'center'
                    },
                },
                series: [
                    {
                        name:'收入结构报表',
                        type:'pie',
                      clickable:sel,
                        radius: ['55%', '70%'],
                        avoidLabelOverlap: false,
                        label: {
                            normal: {
                                show: true,
                                position: 'center',
                                formatter:function(){
                                    return v;
                                },
                                data:total,
                                fontSize:18,
                                fontWeight:600,
                                color:'#000',
                                padding:[24,0],
                            },
                            emphasis: {
                                show: true
                            }
                        },
                        labelLine: {
                            normal: {
                                show: false
                            }
                        },
                        data:data,
                        showInLegend: true
                    }
                ],
                color:color,
            })
            this.chart.hideLoading()
        },
        // 明细列表接口
        transactionList(page,pagesize,todayNum){
            var so=sorts();
            var uid=cookie.get('uid');
            var access_token=cookie.get('access_token');
            var json={
              page:page,
              pagesize:pagesize,
              month:this.year+'-'+this.mouth+'-'+'01',
              sorts:so,
              uid:uid,
              access_token:access_token
            }
            var si=sign(json);
            json['sign']=si;
            // post，get请求
            getMoneyFlow(json).then((res) => {
              let vue=this;
                if(res.code==40013){
                    vue.$router.push({name: 'login', params: {}});
                    return false;
                }
                if(res.code==2000){
                  var jm=Decrypt(res.data);
                  jm=JSON.parse(jm);
                  // var jm=res.data;
                  this.totalList=jm;
                  if(this.totalList.expend>9999.99){
                    this.totalList.expend=this.totalList.expend/10000;
                    this.exp='万元';
                    this.n1=3;
                  }else{
                    this.exp='元';
                    this.n1=2;
                  }
                  if(this.totalList.income>9999.99){
                    this.totalList.income=this.totalList.income/10000;
                    this.inc='万元';
                    this.n2=3;
                  }else{
                    this.inc='元';
                    this.n2=2;
                  }
                  if(page==1){
                    this.monthList={};
                  }
                  for(var j in jm){
                    if(jm[j]!='' && jm[j] instanceof Object){
                      if(this.monthList[j]==undefined){
                        this.monthList[j]={};
                      }
                      if(this.monthList[j]['day']==undefined){
                        this.monthList[j]['day']=[];
                      }
                      for(var v in jm[j]){
                        if(jm[j][v]!='' && jm[j][v] instanceof Object){
                          this.monthList[j]['expend']=jm[j]['expend'];
                          this.monthList[j]['income']=jm[j]['income'];
                          this.monthList[j]['time']=jm[j]['time'];
                          this.monthList[j]['totaldays']=jm['totaldays'];
                          var fuhao=jm[j][v]['type']==1?'+':'-';
                          var pay=payType[jm[j][v]['pay_type']];
                          var json={
                            label:pay,
                            value:fuhao+jm[j][v]['money']
                          }
                          this.monthList[j]['day'].push(json);
                          this.dayList=this.monthList[j]['day'];
                        }
                      }
                    }
                  }
                  this.onFetching = false;
              }
            })
        },
        // 当前日期
        setToday () {
            let now = new Date()
            let cmonth = now.getMonth() + 1
            let day = now.getDate()
            if (cmonth < 10) cmonth = '0' + cmonth
            if (day < 10) day = '0' + day
            let data= now.getFullYear() + '-' + cmonth + '-' + day
            this.year=now.getFullYear()
            this.mouth=cmonth
            this.date=data
          this.todayNum=data;
          this.today=data;
        },

    }
  }
</script>
<style lang="less" scoped>
@hong:#cf0808;
@blue:#1babe3;
#Account{
  overflow: hidden;
  .borderR{
    border-right:1px dashed #cccccc;
    span{
      margin-top:0px !important;
      font-size: 34px !important;
      font-weight: bold !important;
    }
  }
  .card-demo-flex {
    display: flex;
  }
  .card-demo-content01 {
    padding: 15px 0 8px;
  }
  .card-padding {
    padding: 15px;
  }
  .card-demo-flex > div {
    flex: 1;
    text-align: center;
    font-size: 12px;
    padding-left: 0.5rem;
  }
  .card-demo-flex > div:nth-child(2){
    padding-left: 0.5rem;
  }
  .card-demo-flex span {
    color: #000000;
  }
  .account{
    background-color: #ebebeb;
    p{
      text-align: left;
      font-size: 13px;
    }
    span{
      display: block;
      font-size: 22px;
      font-weight: bold;
      text-align: left;
      margin-top:13px;
    }
    i{

      font-size: 16px;
      font-weight: normal;
      color: #000000;
      position: relative;
      top:-2px;
    }
  }
  .center {
    padding-top: 10px;
    padding-left: 15px;
    color: green;
  }
  .weui-cell:before{
    border:none !important;
  }
  .vux-datetime{
    width: 95px;
    height: 50px;
    margin-top:-50px;
    .weui-cell__ft{
      display: none;
    }
  }
  .vux-slider{
    margin-top:5px;
  }
  #main,#main2{
    width: 8rem;
    height: 6rem;
    margin: 10px auto 10px;
  }
  .pay-tit{
    border-top: 1px solid #d9d9d9;
  }
  .scDiv{
    overflow-y: auto;
  }
}

</style>
